package client;

import org.openmuc.j60870.*;
import org.openmuc.j60870.ie.*;

import java.io.IOException;

/**
 * @Author : 托马斯
 * @Date : 2025/6/27 8:48
 * @Description :
 */
public class IEC104Listener implements ConnectionEventListener {

    @Override
    public void newASdu(Connection connection, ASdu aSdu) {
        // 获取基本信息
        ASduType type = aSdu.getTypeIdentification();
        CauseOfTransmission cot = aSdu.getCauseOfTransmission();
        int commonAddress = aSdu.getCommonAddress();
        System.out.println("==============");

        System.out.println("ASdu 类型: " + type);
        System.out.println("传输原因: " + cot);
        System.out.println("公共地址: " + commonAddress);

        // 解析信息对象
        InformationObject[] informationObjects = aSdu.getInformationObjects();
        for (InformationObject informationObject : informationObjects) {
            System.out.println("信息对象地址: " + informationObject.getInformationObjectAddress());
            InformationElement[][] informationElements = informationObject.getInformationElements();
            for (int i = 0; i < informationElements.length; i++) {
                InformationElement[] elements = informationElements[i];
                // 1.总召 ======================
                if (type == ASduType.C_IC_NA_1) {
                    // 总召确认
                    if (cot == CauseOfTransmission.ACTIVATION_CON) {

                    }
                    // 总召结束
                    else if (cot == CauseOfTransmission.ACTIVATION_TERMINATION) {

                    }

                    if (elements != null && elements.length > 0) {
                        // 总召上行的对象类型
                        if (elements[0] instanceof IeQualifierOfInterrogation) {
                            IeQualifierOfInterrogation qoi = (IeQualifierOfInterrogation) elements[0];

                        }
                    }
                }
                // 2.初始化结束 ======================
                else if (type == ASduType.M_EI_NA_1) {
                    System.out.println("初始化结束");
                }
                // 3.单点遥信 ======================
                else if (type == ASduType.M_SP_NA_1) {
                    if (elements[0] instanceof IeSinglePointWithQuality) {
                        IeSinglePointWithQuality singlePoint = (IeSinglePointWithQuality) elements[0];
                        boolean value = singlePoint.isOn();
                        System.out.println("单点遥信值：" + (value ? "闭合" : "断开"));
                    }
                }
                // 4.单点遥测 ======================
                else if (type == ASduType.M_ME_NC_1) {
                    if (elements[0] instanceof IeShortFloat) {
                        IeShortFloat shortFloat = (IeShortFloat) elements[0];
                        System.out.println(String.format("测量值：%s", shortFloat.getValue()));
                    }
                }
                // 5.遥控确认 ======================
                else if (type == ASduType.C_SC_NA_1) {
                    if (elements[0] instanceof IeSingleCommand) {
                        IeSingleCommand singleCommand = (IeSingleCommand) elements[0];
                        System.out.println("遥控确认：" + ((singleCommand).isCommandStateOn() ? "闭合" : "断开"));
                    }
                } else {
                    // todo 补充其他类型
                }

            }
        }

    }

    @Override
    public void connectionClosed(Connection connection, IOException cause) {
        System.err.println(cause.getMessage());
    }

    @Override
    public void dataTransferStateChanged(Connection connection, boolean stopped) {
        if (stopped) {
            System.out.println("数据传输：停止");
            return;
        }
        System.out.println("数据传输：启动，准备发送测试命令...");
        // ... 比如发送 总召
        callC_IC_NA_1(connection, 1);
    }

    /**
     * 总召
     */
    public void callC_IC_NA_1(Connection connection, int commonAddress) {
        try {
            connection.interrogation(
                    commonAddress, // 公共地址
                    CauseOfTransmission.ACTIVATION, // 6
                    new IeQualifierOfInterrogation(20) // 召唤限定词，默认20，表示全站总召唤
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 遥控
     */
    public void callC_SC_NA_1(Connection connection, int commonAddress, int informationObjectAddress, boolean commandStateOn) {
        InformationObject informationObject = new InformationObject(
                informationObjectAddress,
                new IeSingleCommand(commandStateOn, 0, false)
        );

        ASdu asdu = new ASdu(
                ASduType.C_SC_NA_1,
                true,
                CauseOfTransmission.ACTIVATION,
                false,
                false,
                0,
                commonAddress,
                informationObject
        );

        try {
            connection.send(asdu);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
